package io.gitee.tuo_tuo.jfinaldevassistance;


import java.util.HashMap;
import java.util.Map;

/**
 * @author tuotuo
 * Description: 通用统一返回结果类
 */
public class Result {

    public static final int SUCCESS = 1; //成功
    public static final int FAIL = -1; //失败
	public static final int NO_LOGIN = -401; //失败

	protected int code;
	protected String msg;
	protected Object data;

    public Result(boolean success){
        this.code = success ? SUCCESS : FAIL;
        this.msg = success ? "成功" : "失败";
    }

    public Result(boolean success, String msg){
        this.code = success ? SUCCESS : FAIL;
        this.msg = msg;
    }

	public Result(int code, String msg){
		this.code = code;
		this.msg = msg;
	}

	/**
	 * 新版写法
	 */
    public static Result ok(){
		Result result = new Result(true);
		return result;
	}

	/**
	 * 新版写法
	 */
	public static Result fail(){
		Result result = new Result(false);
		return result;
	}
	/**
	 * 新版写法
	 */
	public static Result create(boolean success, String successMsg, String failMsg){
		Result result = success ? Result.ok().setMsg(successMsg) : Result.fail().setMsg(failMsg);
		return result;
	}

    public Result setData(String key, Object value) {
    	if(data != null && data instanceof Map == false){
			throw new RuntimeException("Result.data 不是Map类型");
		}else if(this.data == null){
    		data = new HashMap<String, Object>();
		}
		((Map)data).put(key, value);
        return this;
    }

	public int getCode() {
		return code;
	}

	public Result setCode(int code) {
		this.code = code;
		return this;
	}

	public String getMsg() {
		return msg;
	}

	public Result setMsg(String msg) {
		this.msg = msg;
		return this;
	}

	public Object getData() {
		return data;
	}

}